<template>
<div>
  <a-card style="width: 100%">
    <a-form :form="form">
      <a-row>
        <a-col :md="8" :sm="12">
          <a-form-item
            :label="$t('key.kkyx')"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['kcyx',
              {
                rules: [{ required: true, message: '请选择开课院系!' }],
              }]" @change="yxChange" showSearch :filterOption="filterOption" :disabled="!!editId">
              <a-select-option v-for="i in selectMenu.yxList" :key="i.id" :value="i.dwh">{{ i.dwh+'-'+i.dwmc }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            :label="$t('key.kcmc')"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['kcdm',
              {
                rules: [{ required: true, message: '请选择课程!' }],
              }]" @change="kcChange" showSearch :filterOption="filterOption" :disabled="!!editId">
              <a-spin v-if="kcLoading" slot="notFoundContent" size="small"/>
              <a-select-option v-for="(i,index) in selectMenu.courseList" :key="index" :value="i.kch">{{ i.kch + '-' + i.kcmc }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            :label="$t('key.ksnj')"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['ksnj',
              {
                rules: [{ required: true, message: '请选择考试年级!' }],
              }]">
              <a-select-option v-for="i in TYPE0126" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            :label="$t('key.ksxn')"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['ksxn',
              {
                rules: [{ required: true, message: '请选择考试学年!' }],
              }]">
              <a-select-option v-for="i in TYPE0125" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            :label="$t('key.ksxq')"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['ksxq',
              {
                rules: [{ required: true, message: '请选择考试学期!' }],
              }]">
              <a-select-option v-for="i in TYPE0072" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            :label="$t('key.ksxz')"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['ksxz',
              {
                rules: [{ required: true, message: '请选择考试性质!' }],
              }]">
              <a-select-option v-for="i in TYPE0358" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            :label="$t('key.kslb')"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['kslb',
              {
                rules: [{ required: true, message: '请选择考试类别!' }],
                initialValue: '1'
              }]">
              <a-select-option v-for="i in TYPE0109" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            :label="$t('key.cjlx')"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['cjlx',
              {
                rules: [{ required: true, message: '请选择成绩类型!' }],
                initialValue: '01'
              }]">
              <a-select-option v-for="i in TYPE0328" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            :label="$t('key.ksrq')"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-date-picker v-decorator="['ksrq',
              {
                rules: [{ required: true, message: '请选择开始时间!' }],
              }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="12">
          <a-button style="margin-left: 50px;" type="primary" @click="startAdd">{{ $t('button.startRecordingResults') }}</a-button>
          <a-button style="margin-left: 25px;" type="primary" @click="exportEcl" :disabled="hasErrors(form.getFieldsError())" >导出</a-button>
          <a-button style="margin-left: 25px;" type="primary" @click="exportExam" :disabled="hasErrors(form.getFieldsError())">下载成绩模版</a-button>
          <!-- <a-button type="primary" @click="$refs.table.refresh(true)" style="margin:0 10px">{{ $t('button.query') }}</a-button> -->
        </a-col>
        <a-col :md="12" :sm="12" style="text-align:right">
        <div>
            <a-upload
              :fileList="fileList"
              :remove="handleRemove"
              :beforeUpload="beforeUpload"
            >
              <a-button type="primary" :disabled="hasErrors(form.getFieldsError())" >选择文件</a-button>
              <a-button
                type="primary"
                @click.stop="handleImport"
                :disabled="fileList.length === 0"
                :loading="uploading"
              >
                {{uploading ? 'Uploading' : '导入' }}
              </a-button>
            </a-upload>
          </div>
          </a-col>
      </a-row>
    </a-form>
    <add-modal
      ref="add"
      :visible="visible"
      :TYPE0519="TYPE0519"
      :modelForm = modelForm
      @cancel="visible = false"
      @refresh="$refs.table.refresh(false)"
    />
  </a-card>
  <a-card :bordered="false" style="margin-top: 10px">
      <s-table
        ref="table"
        size="default"
        rowKey="index"
        :columns="columns"
        :data="loadData"
        :alert="{show: false}"
        :pagination="{ pageSize: 10 }"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>

        <template slot="operation" slot-scope="text, record">
          <a @click="editThis(record,true)">{{ $t('button.showStu') }}</a>
          <a v-if="record.cjztm == '01'|| record.cjztm == '03'" @click="editThis(record,false)">{{ $t('button.xg') }}</a>
           <a v-if="record.cjztm == '01'" @click="submit(record.id)">{{ $t('button.submit') }}</a>
        </template>
      </s-table>
    </a-card>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import { STable } from '~'
import { DateToString } from '@/utils/common'
import addModal from './components/addModal'

function hasErrors(fieldsError) {
  return Object.keys(fieldsError).some(field => fieldsError[field]);
}
export default {
  data () {
    return {
      hasErrors,
      uploading: false,
      fileList: [],
      form: this.$form.createForm(this),
      selectMenu: {},
      kcLoading: false,
      editId: null,
      visible: false,
      modelForm:{},
      queryParam: {},
      columns: [
//         {
//           title: this.$t('key.no'),
//           scopedSlots: { customRender: 'serial' }
//         },
        {
          title: this.$t('key.kkyx'),
          dataIndex: 'ksyxmc'
        },
        {
          title: this.$t('key.kcmc'),
          dataIndex: 'kcmc'
        },
        {
          title: this.$t('key.ksnj'),
          dataIndex: 'ksnj'
        },
        {
          title: this.$t('key.ksxn'),
          dataIndex: 'ksxn'
        },
        {
          title: this.$t('key.ksxq'),
          dataIndex: 'ksxqmc'
        },
        {
          title: this.$t('key.ksrq'),
          dataIndex: 'ksrq'
        },
        {
          title: this.$t('key.gxsj'),
          dataIndex: 'createDate'
        },
        {
          title: this.$t('key.zt'),
          dataIndex: 'cjztmc'
        },
        {
          title: this.$t('key.option'),
          width: '160px',
          dataIndex: 'id',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      loadData: parameter => {
        parameter.pageNum = parameter.pageNo
        let params = Object.assign(this.queryParam, parameter)
        return this.$api.cultivate.ycjruList(params).then(res => {
            res.data.rows.map(item =>{
                if(item.cfsj)item.cfsj=moment(item.cfsj).format('YYYY-MM-DD')
            })
          return {
            data: res.data.rows ? res.data.rows : [],
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalPage: Math.ceil(res.data.total / parameter.pageSize),
            totalCount: res.data.total
          }
        })
      },
    }
  },
  components: {addModal,STable},
  computed: {
    ...mapState({
      TYPE0125: state => state.app['TYPE0125'],
      TYPE0126: state => state.app['TYPE0126'],
      TYPE0072: state => state.app['TYPE0072'],
      TYPE0358: state => state.app['TYPE0358'],
      TYPE0109: state => state.app['TYPE0109'],
      TYPE0328: state => state.app['TYPE0328'],
      TYPE0519: state => state.app['TYPE0519'],
    })
  },
  activated(){
    this.$store.dispatch('app/sysInfo', true).then(data => {
              console.log(data)
              if ( +new Date() > +data.cjlrjssj  ||  +new Date() < +data.cjlrkssj) {
                this.$confirm({
                  title: '当前不在成绩录入时间范围，无法进行操作',
                  centered: true,
                  okText: '确认',
                  cancelText: '返回',
                  onOk: () => {
                    this.$router.back()
                  },
                  onCancel: () => {
                    this.$router.back()
                  }
                })
              }
            })
  },
  created () {
    this.$store.dispatch('app/setDictionary', 'TYPE0125')
    this.$store.dispatch('app/setDictionary', 'TYPE0126')
    this.$store.dispatch('app/setDictionary', 'TYPE0072')
    this.$store.dispatch('app/setDictionary', 'TYPE0358')
    this.$store.dispatch('app/setDictionary', 'TYPE0109')
    this.$store.dispatch('app/setDictionary', 'TYPE0328')
    this.$store.dispatch('app/setDictionary', 'TYPE0519')
    this.initSelectMenu()
  },
  methods: {
    submit(id){
      this.$api.cultivate.dkcjtj({id}).then(res => {
          this.$message.success(res.msg || '提交成功')
          console.log(res)
          this.$refs.table.refresh(true)
      })

    },
    editThis(item,bool){
      this.$api.cultivate.cjruList({id:item.id}).then(res => {
          console.log(res)
          this.modelForm = {
            kcyx: item.ksyxm,
            kcdm: item.kcbm,
            ksnj: item.ksnj,
            ksxn: item.ksxn,
            ksxq: item.ksxqm,
            ksxz: item.ksxzm,
            kslb: item.kslbm,
            cjlx: item.cjlxm,
            ksrq: item.ksrq,
          }
          this.$refs.add.isEdit = bool
          this.visible = true
          this.$refs.add.cjksxsmdList = typeof res.data === 'object' ? res.data : []
          this.$refs.add.params = this.modelForm
          this.$refs.add.id = item.id
      })
    },
    exportEcl(){
       this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        DateToString(values)
        this.$export('foster/kccj/exportExcel',values)
        })
    },
    exportExam(){
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        DateToString(values)
        this.$export('foster/kccj/exportExcelMb',values)
        })
    },
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload (file) {
      this.fileList = [...this.fileList, file]
      return false
    },
    handleImport () {
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
      const { fileList } = this
      const formData = new FormData()
      fileList.forEach((file) => {
        formData.append('file', file)
      })
      console.log('formData:',formData)
      console.log('fileList:',fileList)
      this.uploading = true
      this.$upload('foster/kccj/drdkcjUpload',formData).then( res => {
        // this.$message.success("导入成功")
        this.uploading = false
        let params = res.data
        for(let i=0;i<params.length;i++){
          params[i].cjlxm=this.form.getFieldsValue().cjlx
          params[i].xsxh = params[i].xh
        }
        DateToString(values)
        let submitObj={
          cjlx: values.cjlx,
          kcdm: values.kcdm,
          kcyx: values.kcyx,
          kslb: values.kslb,
          ksnj: values.ksnj,
          ksrq: values.ksrq,
          ksxn: values.ksxn,
          ksxq: values.ksxq,
          ksxz: values.ksxz,
          cjksxsmdList: params,
          sftj: true,
        }
      this.$api.cultivate.kccjDkcjlrAdd(submitObj).then(res => {
          this.$message.success(res.msg || '导入成功')
          console.log(res)
      })
      this.$refs.table.refresh(true)
      })

       })
      console.log('开始导入')
    },
    initSelectMenu () {
      let allRequest = [
        this.$api.cultivate.teacherClientYX()
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          yxList: res[0].data
        }
      })
    },
    filterOption (value, op) {
      return op.componentOptions.children[0].text.indexOf(value) !== -1
    },
    yxChange (code) {
      this.$nextTick(() => {
        this.form.setFieldsValue({kcdm: ''})
        this.$set(this.selectMenu, 'courseList', [])
        if (code) {
          this.kcLoading = true
          this.$api.cultivate.teacherClientZY({ssyxm: code}).then(res => {
            this.$set(this.selectMenu, 'courseList', res.data)
          }).finally(() => {
            this.kcLoading = false
          })
        } else {
          this.$set(this.selectMenu, 'courseList', [])
        }
      })
    },
    kcChange (kch) {
      let kc = this.selectMenu.courseList.find(kc => {
        return kc.kch === kch
      })
      this.form.setFieldsValue({
        xf: kc.xf
      })
    },
    startAdd () {
      this.form.validateFields((err, values) => {
        if (err) return
        DateToString(values)
        this.$api.cultivate.kccjDkcjlrxsList(values).then(res => {
          this.visible = true
          this.modelForm = values
          this.$refs.add.cjksxsmdList = typeof res.data === 'object' ? res.data : []
          this.$refs.add.params = values
        })
      })
    }
  }
}
</script>

<style>

</style>
